package handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.ThreadLocalRandom;

/** 服务端辅助处理类
 * @program: hw
 * @description: qiuheyi
 * @author: qhy
 * @create: 2020-08-07 08:49
 **/
public class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    /**
     * 广播内容
     */
    private static final String[] DICTIONARY = {"79  93  d  7a  4f  ef  a4  d8  a0  b0  \n" +
            "40  a0  71  9  1e  d1  d4  a4  5f  6f  \n" +
            "7e  50  d0  c9  1a  41  26  c  c1  a  \n" +
            "a  1e  c  6d  6c  87  64  11  89  d6  "};

    private String nextQuote() {
        //线程安全岁基类，避免多线程环境发生错误
        int quote = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
        return DICTIONARY[quote];
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    /**
     * //接收Netty封装的DatagramPacket对象，然后构造响应消息
     * @param ctx
     * @param packet
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        //利用ByteBuf的toString()方法获取请求消息
        String req = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println(req);
//        ctx.writeAndFlush();
    }
}
